package com.lhf.aicloud.utils;

import io.minio.*;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @author : lhf
 * @date : Created in 2024/07/28
 * @description: 类的描述
 */
@Component
public class MinIoUtil {
    @Resource
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    public String upload(String fileName, InputStream inputStream, String contentType) throws Exception {
        // 判断桶是否存在
        boolean isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(this.bucketName).build());
        // 不存在则创建
        if (!isExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(this.bucketName).build());
        }
        // 上传文件
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(this.bucketName)
                .object(fileName)
                .stream(inputStream, -1, 10485760)
                .contentType(contentType)
                .build());
        // 获取文件访问地址
//        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
//                .bucket(this.bucketName)
//                .object(fileName)
//                .method(Method.GET)
//                .build());
        return endpoint + "/" + this.bucketName + "/" + fileName;

    }
}
